import { deriveKey, encrypt } from './crypto_front.js';
import { config } from './config.js';

class Auth {
    constructor() {
        this.loginBtn = document.getElementById('login-btn');
        this.emailInput = document.getElementById('email');
        this.passwordInput = document.getElementById('password');
        this.forgotPasswordLink = document.getElementById('forgot-password');
        
        this.init();
    }

    init() {
        this.loginBtn.addEventListener('click', () => this.handleLogin());
        this.forgotPasswordLink.addEventListener('click', (e) => this.handleForgotPassword(e));
    }

    async handleLogin() {
        const email = this.emailInput.value;
        const password = this.passwordInput.value;

        if (!this.validateEmail(email) || !this.validatePassword(password)) {
            alert('请输入有效的邮箱和密码（密码至少8位）');
            return;
        }

        try {
            // 1. 检查用户是否存在
            const checkResponse = await fetch(`${config.API_BASE_URL}/api/auth/check-user`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email })
            });

            if (!checkResponse.ok) {
                const error = await checkResponse.json();
                throw new Error(error.message || '检查用户失败');
            }

            const { exists } = await checkResponse.json();
            console.log('Frontend check user response:', { exists });

            // 2. 获取challenge和salt
            const challengeResponse = await fetch(`${config.API_BASE_URL}/api/auth/challenge`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email })
            });

            if (!challengeResponse.ok) {
                const error = await challengeResponse.json();
                throw new Error(error.message || '获取challenge失败');
            }

            const { challenge, authSalt, encryptSalt } = await challengeResponse.json();
            console.log('Frontend challenge response:', { challenge, authSalt, encryptSalt });
            
            // 3. 使用PBKDF2生成两个密钥
            const authKey = await deriveKey(password, authSalt);
            const encryptKey = await deriveKey(password, encryptSalt);
            
            // 4. 使用认证密钥加密challenge
            const { encrypted: encryptedChallenge, iv } = await encrypt(challenge, authKey);
            console.log('Frontend login request:', { email, encryptedChallenge, iv });
            
            // 5. 发送登录请求
            const loginResponse = await fetch(`${config.API_BASE_URL}/api/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email,
                    encryptedChallenge,
                    iv,
                    authKey : exists ? undefined : authKey,
                    encryptKey
                })
            });

            if (!loginResponse.ok) {
                const error = await loginResponse.json();
                throw new Error(error.message || '登录失败');
            }

            const { token, masterKeyId } = await loginResponse.json();
            
            // 保存token、email和masterKeyId
            localStorage.setItem('token', token);
            localStorage.setItem('email', email);
            // 将encryptKey保存到session中，关闭浏览器后删除
            // sessionStorage.setItem('encryptKey', encryptKey);   
            
            // 登录成功后跳转到主页面
            window.location.href = 'dashboard.html';
            
        } catch (error) {
            console.error('登录失败:', error);
            alert(error.message || '登录失败，请重试');
        }
    }

    validateEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    validatePassword(password) {
        return password.length >= 8;
    }

    async handleForgotPassword(e) {
        e.preventDefault();
        const email = this.emailInput.value;
        if (!this.validateEmail(email)) {
            alert('请输入有效的邮箱地址');
            return;
        }

        // 发送重置密码请求
        fetch(`${config.API_BASE_URL}/api/auth/forgot-password`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                throw new Error(data.message || data.error);
            }
            alert('重置密码链接已发送到您的邮箱，请查收');
        })
        .catch(error => {
            console.error('发送重置密码邮件失败:', error);
            alert(error.message || '发送重置密码邮件失败，请重试');
        });
    }
}

// 初始化认证功能
document.addEventListener('DOMContentLoaded', () => {
    new Auth();
}); 